package com.sgb.kjwl.view.ui.activity.enterprise;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityEnterpriseInquireByLetterBinding;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.enterprise.FilePictureEntity;
import com.sgb.kjwl.model.entity.pick.UserInquiryForTender;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.MemberEvent;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.sgb.kjwl.view.widget.enterprise.AddContentListView;
import com.sgb.kjwl.viewmodel.enterprise.EnterpriseInquireByLetterModel;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.util.SharedPreferenceUtil;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业服务函询
 */
public class EnterpriseInquireByLetterActivity extends AppActivity {

    EnterpriseInquireByLetterModel viewModel;

    private ActivityEnterpriseInquireByLetterBinding binding;
    private ImageAdapter adapter;
    //    private ContentAdapter contentAdapter;
    private List<String> urls;
    private List<File> fileList;
    public int imgTotal;
    private int currentImgNum;
    private List<String> uploadImgList = new ArrayList<>();

    private ArrayList<UserInquiryForTender.AddCustomListBean> customFieldListBeans = new ArrayList<>();//新增字段
    private List<FilePictureEntity> fileImageList = new ArrayList<>();
    private String businessId = "";
    private String businessTitle = "";
    private String answerCompanyName = "";
    private String answerCompanyNo = "";
    private String answerUserName = "";
    private String answerUserNo = "";

    private String businessType = "";//业务类型 1 转让 2需求  3 服务 4 团队
    private String enterpriseType = "";//企业服务类型 1 服务大厅 2商标转让 3 专利转让 4 版权转让 5 公司转让 6资产转让 7需求大厅 8专业团队
    private Map<String, Object> map = new HashMap<>();
    private String enquiryType = "";//函询类型

    private int[] selectPosition = new int[1];
    private List<PickSelectEntity> pickSelectEntityList = new ArrayList<>();
    List<LocalMedia> selectList = new ArrayList<>();


    public static void start(Context context, String businessType, String enterpriseType, String businessId, String businessTitle,
                             String answerCompanyName, String answerCompanyNo, String answerUserName, String answerUserNo) {
        Intent intent = new Intent();
        intent.putExtra("businessType", businessType);
        intent.putExtra("enterpriseType", enterpriseType);
        intent.putExtra("businessId", businessId);
        intent.putExtra("businessTitle", businessTitle);
        intent.putExtra("answerCompanyName", answerCompanyName);
        intent.putExtra("answerCompanyNo", answerCompanyNo);
        intent.putExtra("answerUserName", answerUserName);
        intent.putExtra("answerUserNo", answerUserNo);
        intent.setClass(context, EnterpriseInquireByLetterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_enterprise_inquire_by_letter);
        viewModel = new ViewModelProvider(this).get(EnterpriseInquireByLetterModel.class);
        binding.ivAddAns.setOnClickListener(this);
        binding.tvSubmit.setOnClickListener(this);
        initExtra();
    }

    private void initExtra() {
        businessType = getIntent().getStringExtra("businessType");
        enterpriseType = getIntent().getStringExtra("enterpriseType");
        businessId = getIntent().getStringExtra("businessId");
        businessTitle = getIntent().getStringExtra("businessTitle");
        answerCompanyName = getIntent().getStringExtra("answerCompanyName");
        answerCompanyNo = getIntent().getStringExtra("answerCompanyNo");
        answerUserName = getIntent().getStringExtra("answerUserName");
        answerUserNo = getIntent().getStringExtra("answerUserNo");
    }

    @Override
    protected void onResume() {
        super.onResume();
        binding.tvNum.setText(adapter.getFileList().size() + " / 5");
    }

    @Override
    protected void init() {
        urls = new ArrayList<>();
        fileList = new ArrayList<>();
        adapter = new ImageAdapter(this, null, null, 5);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        binding.recyclerView.setAdapter(adapter);

        binding.ivAddAns.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.rootLayout.getChildCount() < 5) {
                    setAddUseable(false);
                    if (binding.rootLayout.getChildCount() > 0) {
                        if (checkItemInput(true)) {
                            AddContentListView pickDetailListView = new AddContentListView(EnterpriseInquireByLetterActivity.this);
                            binding.rootLayout.addView(pickDetailListView);
                            pickDetailListView.OnInputContent(new AddContentListView.IInputContent() {
                                @Override
                                public void hasContent() {
                                    if (binding.rootLayout.getChildCount() < 5)
                                        setAddUseable(true);
                                }

                                @Override
                                public void hasNoContent() {
                                    setAddUseable(false);
                                }
                            });
                            pickDetailListView.setItemChildCLickListener(new AddContentListView.ItemChildCLickListener() {
                                @Override
                                public void deletePos() {
                                    binding.rootLayout.removeView(pickDetailListView);
                                    setAddUseable(checkItemInput(false));
                                }
                            });
                        }
                    } else {
                        AddContentListView pickDetailListView = new AddContentListView(EnterpriseInquireByLetterActivity.this);
                        binding.rootLayout.addView(pickDetailListView);
                        pickDetailListView.OnInputContent(new AddContentListView.IInputContent() {
                            @Override
                            public void hasContent() {
                                if (binding.rootLayout.getChildCount() < 5)
                                    setAddUseable(true);
                            }

                            @Override
                            public void hasNoContent() {
                                setAddUseable(false);
                            }
                        });
                        pickDetailListView.setItemChildCLickListener(new AddContentListView.ItemChildCLickListener() {
                            @Override
                            public void deletePos() {
                                binding.rootLayout.removeView(pickDetailListView);
                                setAddUseable(checkItemInput(false));
                            }
                        });
                    }

                } else {
                    MToast.showLongToast(getApplicationContext(), "最多添加5条");
                }
            }
        });

        viewModel.tenderInquiryType(this, businessType);
        viewModel.tenderingTypeLD.observe(this, this::setInquiryType);
        viewModel.saveSuccess.observe(this, a -> {
            finish();
            EventBus.getDefault().postSticky(MemberEvent.make().setMessageTag(EventConstant.EVENT_REPORT_INQUIRE_FINISH));
        });
        viewModel.uploadRefresh.observe(this, this::uploadRefresh);


    }

    /**
     * 设置新增按钮是否可点击
     *
     * @param useable true可用
     */
    public void setAddUseable(boolean useable) {
        if (useable) {
            binding.ivAddAns.setAlpha(1);
            binding.ivAddAns.setClickable(true);
        } else {
            binding.ivAddAns.setAlpha(0.5f);
            binding.ivAddAns.setClickable(false);
        }
    }

    public void setInquiryType(List<PickSelectEntity> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        pickSelectEntityList = data;
        selectPosition[0] = 0;
        final LayoutInflater mInflater = LayoutInflater.from(EnterpriseInquireByLetterActivity.this);
        TagAdapter tagAdapter = new TagAdapter<PickSelectEntity>(data) {
            @Override
            public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, PickSelectEntity pickSelectEntity) {
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_enterprise_inquire_by_letter, binding.typeList, false);
                TextView tv = layout.findViewById(R.id.name);
                int width = ResolutionUtil.getScreenWidth(EnterpriseInquireByLetterActivity.this) - ResolutionUtil.dp2px(getActivity(), 75);
                tv.setMinWidth(width / 4);
                tv.setText(pickSelectEntity.getProjectscale());
                if (selectPosition[0] >= 0) {
                    if (position == selectPosition[0]) {
                        tv.setBackgroundResource(R.drawable.bg_report_enterprise_red_select);
                        tv.setTextColor(getResources().getColor(R.color.color_main));
                    } else {
                        tv.setBackgroundResource(R.drawable.bg_report_enterprise_type_normal);
                        tv.setTextColor(getResources().getColor(R.color.color_333333));
                    }
                }
                return layout;
            }
        };
        if (data != null && data.size() > 0) {
            enquiryType = data.get(0).getNo();
        }
        binding.typeList.setAdapter(tagAdapter);
        binding.typeList.setMaxSelectCount(1);
        binding.typeList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, com.zhy.view.flowlayout.FlowLayout parent) {
                enquiryType = data.get(position).getNo();
                selectPosition[0] = position;
                tagAdapter.notifyDataChanged();
                return false;
            }
        });
    }

    private boolean checkItemInput(boolean isShowToast) {
        for (int i = 0; i < binding.rootLayout.getChildCount(); i++) {
            AddContentListView pickLetterListView = (AddContentListView) binding.rootLayout.getChildAt(i);
            if (pickLetterListView.getViewContent()) {
                if (isShowToast) {
//                    MToast.showLongToast(getApplicationContext(), "有新增的标题和内容未填写");
                    DialogHelper.showSingleDialog(this, "", "新增的标题与内容全部填写", "确定", false, new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });

                }
                return false;
            }
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_submit:
                if (!ClickUtils.isDoubleClick()) {
                    if (TextUtils.isEmpty(binding.cfkEdit.getEditContent()) || binding.cfkEdit.getEditContent().length() < 5) {
                        MToast.showLongToast(getApplicationContext(), "请输入疑问事项最少5个字最多200字");
                        return;
                    }
                    if (!checkItemInput(true)) {
                        return;
                    }
                    if (adapter.getFileList().size() != 0) {
                        uploadImgList.clear();
                        imgTotal = adapter.getFileList().size();
                        viewModel.uploadMutiFileModel(this, adapter.getFileList().get(currentImgNum), currentImgNum + 1);
                    } else {
                        uploadImgSuccess(adapter.getUrls(), 1);
                    }
                }
                break;
            case R.id.iv_del:
                break;
        }
    }

    private void uploadImgSuccess(List<String> urls, int type) {
        //拼接图片url
        for (int i = 0; i < urls.size(); i++) {
            FilePictureEntity fileListBean = new FilePictureEntity();
            int picI = i + 1;
            fileListBean.setName("第" + picI + "张图片");
            fileListBean.setUrl(urls.get(i));
            if (type == 0) {
                fileImageList.add(fileListBean);
            }
        }
        for (int i = 0; i < binding.rootLayout.getChildCount(); i++) {
            AddContentListView pickLetterListView = (AddContentListView) binding.rootLayout.getChildAt(i);
            customFieldListBeans.add(pickLetterListView.getContent());
        }
        getFilterJson();

        viewModel.saveUserInquiry(this, map);
    }

    private void getFilterJson() {
        map.put("enquiryType", enquiryType);
        map.put("questionMatters", binding.cfkEdit.getEditContent());
        map.put("comprehend", binding.cfkEdit2View.getEditContent());
        map.put("requestAnswer", binding.cfkEdit3View.getEditContent());
        map.put("customFieldList", GsonManager.getInstance().getGson().toJson(customFieldListBeans));
        map.put("businessType", businessType);
        map.put("enterpriseType", enterpriseType);
        map.put("filedList", com.sgb.kjwl.api.GsonManager.getInstance().getGson().toJson(fileImageList));

        map.put("businessId", businessId);
        map.put("businessTitle", businessTitle);
        map.put("answerCompanyName", answerCompanyName);
        map.put("answerCompanyNo", answerCompanyNo);
        map.put("answerUserName", answerUserName);
        map.put("answerUserNo", answerUserNo);

        if (UserOperating.getInstance().isCompany()) {
            map.put("questionCompanyName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME, ""));
            map.put("questionCompanyNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, ""));
        } else {
            map.put("questionUserName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, ""));
            map.put("questionUserNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, ""));
        }
    }

    //图片单张上传
    public void uploadRefresh(String url) {
        uploadImgList.add(url);
        if (currentImgNum + 1 == imgTotal) {
            uploadImgSuccess(uploadImgList, 0);
        } else {
            currentImgNum++;
            viewModel.uploadMutiFileModel(this, adapter.getFileList().get(currentImgNum), currentImgNum + 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }
    }
}
